package services

import (
	"context"
	"gorm.io/gorm"
	"my-gin-tiktok/app/models"
	"my-gin-tiktok/global"
)

type favoriteService struct{}

var FavoriteService = new(favoriteService)

// CreateFavorite 用户给视频点赞
func (s *favoriteService) CreateFavorite(ctx context.Context, userID, videoID int64) error {
	favorite := models.Favorite{UserID: userID, VideoID: videoID}
	err := global.App.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		err := tx.Create(&favorite).Error
		if err != nil {
			return err
		}
		err = tx.Model(models.User{}).Exec("update user set favorite_count = favorite_count + 1").Error
		if err != nil {
			return err
		}
		err = tx.Model(models.Video{}).Exec("update video set favorite_count = favorite_count + 1").Error
		if err != nil {
			return err
		}
		return nil
	})
	return err
}

// DeleteFavorite 用户取消给视频点赞
func (s *favoriteService) DeleteFavorite(ctx context.Context, userID, videoID int64) error {
	var favorite models.Favorite
	err := global.App.DB.WithContext(ctx).Where("user_id = ? AND video_id = ?", userID, videoID).First(&favorite).Error
	if err != nil {
		return err
	}

	err = global.App.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		err = tx.Delete(models.Favorite{}, favorite.ID).Error
		if err != nil {
			return err
		}
		err = tx.Model(models.User{}).Exec("update user set favorite_count = favorite_count - 1").Error
		if err != nil {
			return err
		}
		err = tx.Model(models.Video{}).Exec("update video set favorite_count = favorite_count - 1").Error
		if err != nil {
			return err
		}
		return nil
	})
	return err
}

// GetFavoriteVideoList 用户点赞视频列表
func (s *favoriteService) GetFavoriteVideoList(ctx context.Context, userID int64) ([]*models.Favorite, error) {
	var favorites []*models.Favorite
	err := global.App.DB.WithContext(ctx).Where("user_id = ?", userID).Find(&favorites).Error
	if err != nil {
		return nil, err
	}
	return favorites, nil
}
